-
Notifications
You must be signed in to change notification settings - Fork 745
/
RewriteController.cs
1935 lines (1714 loc) · 94.4 KB
/
RewriteController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Entities.Urls
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;
using DotNetNuke.Collections.Internal;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Entities.Urls.Config;
using DotNetNuke.Entities.Users;
using DotNetNuke.Services.Localization;
public class RewriteController
{
internal const int SiteRootRewrite = -3;
internal const int AllTabsRewrite = -1;
private static readonly Regex TabIdRegex = new Regex(
@"(?:\?|\&)tabid\=(?<tabid>[\d]+)",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static readonly Regex UrlParamsRegex = new Regex(@"&[^=]+(?:&|$)", RegexOptions.Compiled);
private static readonly Regex CultureMatchRegex = new Regex(
"([A-Za-z]{2})-([A-Za-z]{2})",
RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static readonly Regex LangMatchRegex = new Regex(
"/language/(?<code>.[^/]+)(?:/|$)",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static readonly Regex RewriteParamsRegex = new Regex(
@"(?:\&|\?)(?:(?<key>.[^\=\&]*)\=(?<val>.[^\=\&]*))",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
internal static string CheckLanguageMatch(ref string url, UrlAction result)
{
// ok now scan for the language modifier
Match langMatch = LangMatchRegex.Match(url);
// searches for a string like language/en-US/ in the url
string langParms = string.Empty;
if (langMatch.Success)
{
// OK there is a language modifier in the path
// we want to shift this so it is back on the end where it belongs
langParms = langMatch.Value.TrimEnd('/'); // in the format of /language/en-US only
// it doesn't matter if you get /home.aspx/language/en-US in the url field because the .aspx gets
// removed when matching with the tab dictionary
url = url.Replace(langParms, string.Empty) + langParms;
result.CultureCode = langMatch.Groups["code"].Value; // get the culture code in the requested url
var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList();
if (primaryAliases.Count > 0)
{
string aliasCulture = primaryAliases.GetCultureByPortalIdAndAlias(result.PortalId, result.HttpAlias);
if (aliasCulture != null)
{
// want to do a 301 check because this potentially has a duplicate of portal alias and culture code in the url, which
// is not the best combination
if (result.Action == ActionType.Continue)
{
result.Action = ActionType.CheckFor301;
}
}
}
}
return langParms;
}
/// <summary>appends a language/culture code value if it is not already present in the rewrite path.</summary>
/// <param name="rewritePath"></param>
/// <param name="cultureCode"></param>
/// <returns><see langword="true"/> if the <paramref name="rewritePath"/> was changed, otherwise <see langword="false"/>.</returns>
internal static bool AddLanguageCodeToRewritePath(ref string rewritePath, string cultureCode)
{
bool changed = false;
// 758 : check for any language identifier in the Url before adding a new one, not just the same one
if (!string.IsNullOrEmpty(cultureCode) && !rewritePath.ToLowerInvariant().Contains("language="))
{
changed = true;
if (rewritePath.Contains("?"))
{
rewritePath += "&language=" + cultureCode;
}
else
{
rewritePath += "?language=" + cultureCode;
}
}
return changed;
}
/// <summary>appends a skin value to the rewrite path, as long as there is no existing skin in the path.</summary>
/// <param name="portalId"></param>
/// <param name="rewritePath">The current rewrite path.</param>
/// <param name="skin">The selected skin.</param>
/// <param name="tabId"></param>
/// <param name="message"></param>
/// <remarks>852 : Add skin src to rewrite path for specific aliases.</remarks>
/// <returns><see langword="true"/> if the rewrite path was changed, otherwise <see langword="false"/>.</returns>
internal static bool AddSkinToRewritePath(int tabId, int portalId, ref string rewritePath, string skin, out string message)
{
bool changed = false;
message = null;
TabInfo tab = null;
if (tabId > 0 && portalId > -1)
{
tab = TabController.Instance.GetTab(tabId, portalId, false);
}
// don't overwrite specific skin at tab level for rewritten Urls
if (tab == null || string.IsNullOrEmpty(tab.SkinSrc))
{
if (!string.IsNullOrEmpty(skin) && skin != "default" && !rewritePath.ToLowerInvariant().Contains("skinsrc="))
{
message = "Added SkinSrc : " + skin;
changed = true;
rewritePath += rewritePath.Contains("?") ? "&SkinSrc=" + skin.Replace(".ascx", string.Empty) : "?SkinSrc=" + skin.Replace(".ascx", string.Empty);
}
}
else
{
if (!string.IsNullOrEmpty(tab.SkinSrc))
{
message = "Tab " + tab.TabID.ToString() + " has skin specified : " + tab.SkinSrc;
if (skin != tab.SkinSrc)
{
message += " - " + skin + " not applied due to tab specific skin";
}
}
}
return changed;
}
/// <summary>Checks for exclusions on Rewriting the path, based on a regex pattern.</summary>
/// <param name="result"></param>
/// <param name="requestedPath"></param>
/// <param name="settings"></param>
/// <returns><see langword="true"/> if the requested path is allowed to be rewritten, otherwise <see langword="false"/>.</returns>
internal static bool CanRewriteRequest(UrlAction result, string requestedPath, FriendlyUrlSettings settings)
{
bool retVal;
try
{
// var uri = new Uri(requestedPath);
// if (uri.PathAndQuery.ToLowerInvariant().StartsWith("/default.aspx"))
// {
// retVal = false;
// result.CanRewrite = StateBoolean.True;
// result.RewritePath = uri.PathAndQuery.Substring(1);
// }
// else
// {
if (string.IsNullOrEmpty(settings.DoNotRewriteRegex) ||
!Regex.IsMatch(requestedPath, settings.DoNotRewriteRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))
{
retVal = true;
result.CanRewrite = StateBoolean.True;
}
else
{
retVal = false;
result.CanRewrite = StateBoolean.False;
}
// }
}
catch (Exception ex)
{
retVal = true; // always rewrite if an error in the regex
UrlRewriterUtils.LogExceptionInRequest(ex, "NotSet", result);
result.Ex = ex;
}
return retVal;
}
internal static string CleanExtension(string value, string extension, out bool replaced)
{
return CleanExtension(value, extension, string.Empty, out replaced);
}
internal static string CleanExtension(string value, FriendlyUrlSettings settings, string langParms, out bool replaced)
{
return CleanExtension(value, settings.PageExtension, langParms, out replaced);
}
internal static string CleanExtension(string value, FriendlyUrlSettings settings, out bool replaced)
{
return CleanExtension(value, settings.PageExtension, string.Empty, out replaced);
}
internal static string CleanExtension(string value, string extension, string langParms, out bool replaced)
{
string result = value;
string ext = extension.ToLowerInvariant();
replaced = false;
if (result.EndsWith(ext, StringComparison.InvariantCultureIgnoreCase) && ext != string.Empty)
{
result = result.Substring(0, result.Length - ext.Length);
replaced = true;
}
else
{
if (result.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase))
{
result = result.Substring(0, result.Length - 5);
replaced = true;
}
else
{
// object not set errors when language parameters used
if (string.IsNullOrEmpty(langParms) == false)
{
// safely remove .aspx from the language path without doing a full .aspx -> "" replace on the entire path
if (string.IsNullOrEmpty(result) == false &&
result.EndsWith(".aspx" + langParms, StringComparison.InvariantCultureIgnoreCase))
{
result = result.Substring(0, result.Length - (5 + langParms.Length)) + langParms;
replaced = true;
}
}
else if (result.EndsWith("/"))
{
result = result.Substring(0, result.Length - 1);
replaced = true;
}
}
}
return result;
}
/// <summary>Returns either the rewritten path (if a rewrite used) or the requested path (if no rewrite used).</summary>
/// <param name="result"></param>
/// <param name="requestUri"></param>
/// <returns>Url suitable for input into friendly url generation routine.</returns>
internal static string GetRewriteOrRequestedPath(UrlAction result, Uri requestUri)
{
var pathOnly = result.RewritePath;
if (result.DoRewrite == false)
{
// if no rewrite, then the path should have been a non-friendly path, and therefore can be passed in to get the friendly Url
pathOnly = requestUri.Authority + requestUri.PathAndQuery;
int aliasEnd =
pathOnly.IndexOf(result.PortalAlias.HTTPAlias, StringComparison.InvariantCultureIgnoreCase) +
result.PortalAlias.HTTPAlias.Length;
if (aliasEnd > -1)
{
pathOnly = pathOnly.Substring(aliasEnd);
}
pathOnly = HttpUtility.UrlDecode(pathOnly, Encoding.UTF8);
}
return pathOnly;
}
internal static string GetTabFromDictionary(string url, NameValueCollection querystringCol, FriendlyUrlSettings settings, UrlAction result, Guid parentTraceId)
{
// retrive the tab dictionary from the cache and get the path depth values
int maxAliasPathDepth;
int maxTabPathDepth;
int minAliasPathDepth;
int minTabPathDepth;
int curAliasPathDepth = 0;
var tabDict = TabIndexController.FetchTabDictionary(
result.PortalId,
out minTabPathDepth,
out maxTabPathDepth,
out minAliasPathDepth,
out maxAliasPathDepth,
settings,
false,
result.BypassCachedDictionary,
parentTraceId);
// clean up and prepare the url for scanning
if (url.EndsWith("/"))
{
url = url.TrimEnd('/');
}
// ok now scan for the language modifier
string langParms = CheckLanguageMatch(ref url, result);
// clean off the extension before checking the url matches, but
// remember if an extension existed
bool hadExtension;
string cleanUrl = CleanExtension(url, settings, langParms, out hadExtension);
string[] splitUrl = cleanUrl.Split('/');
// initialise logic switches
bool reWritten = false;
bool finished = false;
string newUrl = CheckIfPortalAlias(url, querystringCol, result, settings, tabDict);
if (newUrl != url)
{
finished = true;
reWritten = true;
}
// start looping through the url segments looking for a match in the tab dictionary
while (finished == false)
{
// first, try forming up a key based on alias/tabpath
int lastIndex = splitUrl.GetUpperBound(0);
int arraySize = lastIndex + 1;
int totalDepth = maxAliasPathDepth + 1 + maxTabPathDepth + 1;
// the maximum depth of segments of a valid url
for (int i = lastIndex; i >= 0; i += -1)
{
// only start checking the url when it is in the range of the min->max number of segments
if (i > minAliasPathDepth & i <= totalDepth)
{
// join all the tab path sections together
// flag to remember if the incoming path had a .aspx or other pageAndExtension on it
int tabPathStart = curAliasPathDepth + 1;
int tabPathLength = i - curAliasPathDepth;
if ((tabPathStart + tabPathLength) <= arraySize)
{
string tabPath = string.Empty;
if (tabPathLength > -1)
{
tabPath = string.Join("/", splitUrl, tabPathStart, tabPathLength);
}
string aliasPath;
if (curAliasPathDepth <= lastIndex)
{
aliasPath = string.Join("/", splitUrl, 0, curAliasPathDepth + 1);
}
else
{
finished = true;
break;
}
int parmsSize = lastIndex - i;
int parmStart = i + 1; // determine if any parameters on this value
// make up the index that is looked for in the Tab Dictionary
string urlPart = aliasPath + "::" + tabPath;
// the :: allows separation of pagename and portal alias
string tabKeyVal = urlPart.ToLowerInvariant(); // force lower case lookup, all keys are lower case
// Try with querystring first If last Index
bool found = false;
if (querystringCol.Count > 0)
{
found = CheckTabPath(tabKeyVal.Replace(" ", settings.SpaceEncodingValue) + "?" + querystringCol.ToString().Split('&')[0].ToLowerInvariant(), result, settings, tabDict, ref newUrl);
}
if (!found)
{
found = CheckTabPath(tabKeyVal.Replace(" ", settings.SpaceEncodingValue), result, settings, tabDict, ref newUrl);
}
bool isSiteRootMatch = false;
if (!found && tabPathLength == 1)
{
// look for special case where the site root has a * value
string siteRootLookup = aliasPath + "::" + "*";
using (tabDict.GetReadLock())
{
found = tabDict.ContainsKey(siteRootLookup);
if (found)
{
isSiteRootMatch = true;
newUrl = tabDict[siteRootLookup];
parmsSize++; // re-increase the parameter size
parmStart--; // shift the point of the parms starting back one
}
}
}
if (found)
{
if (settings.ProcessRequestList != null)
{
newUrl = ReplaceDefaultPage(newUrl, url, settings.ProcessRequestList);
}
// look for a plain match on the default.aspx page which indicates no more rewriting needs to be done
if (!isSiteRootMatch && (newUrl == Globals.glbDefaultPage || newUrl == Globals.glbDefaultPage + "[UseBase]"))
{
// the [UseBase] moniker is a shortcut hack. It's used to recognise pages which have been excluded
// from using Friendly Urls. The request will go on to be processed by the dnn siteurls.config processing.
// this stops the loop and exits the function
newUrl = newUrl.Replace("[UseBase]", string.Empty); // get rid of usebase hack pattern
SetRewriteParameters(ref result, newUrl); // set result
finished = true;
}
else
{
// 708 : move result rewrite set so that downstream functions know the tabid
SetRewriteParameters(ref result, newUrl);
// found the correct rewrite page, now investigate whether there
// is part of the url path that needs to be converted to tab id's
// Multi Language Urls not being rewritten
if (parmsSize > 0)
{
bool rewriteParms = false;
// determine the url action and reason from embedded rewriting tokens
ActionType action;
RedirectReason reason;
string resultingUrl;
RedirectTokens.DetermineRedirectReasonAndAction(
newUrl,
result,
true,
settings,
out resultingUrl,
out reason,
out action);
newUrl = resultingUrl;
result.Action = action;
result.Reason = reason;
// copy the parms into a separate array
var urlParms = new string[parmsSize];
Array.ConstrainedCopy(splitUrl, parmStart, urlParms, 0, parmsSize);
if (!isSiteRootMatch && result.Reason == RedirectReason.User_Profile_Url)
{
result.Reason = RedirectReason.Not_Redirected;
newUrl = RedirectTokens.RemoveAnyRedirectTokensAndReasons(newUrl);
}
// 738 : check for custom module providers
// 894 : allow disable of custom url providers functionality
if (!rewriteParms && settings.EnableCustomProviders)
{
bool newAction;
// newAction tracks whether or not a new 'action' (ie 301, 404, etc) has been requested.
// call the module friendly url providers. Note that the rewriteParms value will be changed if there is a rewrite.
List<string> messages = result.DebugMessages;
newUrl = RewriteParametersFromModuleProvider(
newUrl,
tabKeyVal,
urlParms,
isSiteRootMatch,
result,
settings,
out rewriteParms,
out newAction,
ref messages,
parentTraceId);
result.DebugMessages = messages;
if (newAction)
{
finished = true;
}
}
// do a rewrite on the parameters from the stored parameter regex rewrites
if (!rewriteParms)
{
newUrl = RewriteParameters(
newUrl,
tabKeyVal,
urlParms,
isSiteRootMatch,
result,
out rewriteParms,
parentTraceId);
}
if (rewriteParms && isSiteRootMatch)
{
// set rewrite parameters to take tabid for site root matches
SetRewriteParameters(ref result, newUrl);
}
// if the parms weren't rewritten by means of a regex, then process them normally
// can only try other matches if it wasn't a site root match
if (!rewriteParms && !isSiteRootMatch)
{
// put those parms on the back of the url as a query string
string cultureCode;
newUrl = RewriteParameters(
newUrl,
tabKeyVal,
urlParms,
result,
langParms,
settings,
out cultureCode);
// set culture code if not already set
if (cultureCode != null)
{
result.CultureCode = cultureCode;
}
}
// now check if the request involved a page pageAndExtension, (.aspx) and shouldn't have
if (!finished)
{
// 944 : don't switch to 301 redirect if action already set to 404
if ((settings.PageExtensionUsageType == PageExtensionUsageType.Never
|| settings.PageExtensionUsageType == PageExtensionUsageType.PageOnly) &
hadExtension)
{
// 948 : use new 'no downgrade' method
result.SetActionWithNoDowngrade(ActionType.CheckFor301);
}
else
// 866 : redirect back from no extension to extension if it didn't have one
if (settings.PageExtensionUsageType != PageExtensionUsageType.Never &&
hadExtension == false)
{
// 948 : use new 'no downgrade' method
result.SetActionWithNoDowngrade(ActionType.CheckFor301);
}
}
if (isSiteRootMatch && !finished)
{
// when it was a site root match, this must be matched with a custom parameter regex
// only finished if the parms were rewritten by means of a regex rewrite
reWritten = rewriteParms;
finished = rewriteParms;
}
else
{
// rewriting done
reWritten = true;
finished = true;
}
}
else
{
// determine the url action and redirect reason from embedded tokens in the url rewrite path
string resultUrl;
RedirectReason reason;
ActionType action;
// add back language parameters if they were there
if (string.IsNullOrEmpty(langParms) == false)
{
string[] parms = langParms.Split('/');
if (parms.GetUpperBound(0) >= 1)
{
if (parms[0] == string.Empty && parms.GetUpperBound(0) > 1)
{
newUrl += "&" + parms[1] + "=" + parms[2];
}
else
{
newUrl += "&" + parms[0] + "=" + parms[1];
}
}
}
RedirectTokens.DetermineRedirectReasonAndAction(
newUrl,
result,
false,
settings,
out resultUrl,
out reason,
out action);
newUrl = resultUrl;
result.Reason = reason;
result.Action = action;
if (settings.EnableCustomProviders && ExtensionUrlProviderController.CheckForAlwaysCallProviders(
result.PortalId,
result.TabId,
settings,
parentTraceId))
{
bool newAction;
// newAction tracks whether or not a new 'action' (ie 301, 404, etc) has been requested.
// call the module friendly url providers. Note that the rewriteParms value will be changed if there is a rewrite.
string[] urlParms = new List<string>().ToArray(); // empty parm array
if (string.IsNullOrEmpty(langParms) == false)
{
urlParms = langParms.Split('/');
// split the lang parms into the url Parms
}
bool rewriteParms;
List<string> messages = result.DebugMessages;
newUrl = RewriteParametersFromModuleProvider(
newUrl,
tabKeyVal,
urlParms,
isSiteRootMatch,
result,
settings,
out rewriteParms,
out newAction,
ref messages,
parentTraceId);
result.DebugMessages = messages;
}
// this is a page only, no parameters to deal with
// 944 : don't downgrade to redirect if the current action is a 404 (see 948 for new solution to 944)
if (settings.PageExtensionUsageType == PageExtensionUsageType.Never & hadExtension)
{
// potentially a 301 replaced because shouldn't be using page extensions
// 948 : check to prevent action downgrade, in case already set to redirect
result.SetActionWithNoDowngrade(ActionType.CheckFor301);
}
else
{
// 866 : redirect back from no extension to extension if it didn't have one
if (settings.PageExtensionUsageType != PageExtensionUsageType.Never &&
hadExtension == false)
{
result.SetActionWithNoDowngrade(ActionType.CheckFor301);
}
}
// rewriting done
reWritten = true;
finished = true;
}
}
if (finished)
{
break;
}
}
}
}
}
// next, try forming up a key based on alias1/alias2/tabpath
if (!finished)
{
curAliasPathDepth += 1;
// gone too deep
if ((curAliasPathDepth > maxAliasPathDepth) && !reWritten)
{
// no hope of finding it then
if (!Globals.ServicesFrameworkRegex.IsMatch(url) && result.RedirectAllowed)
{
// nothing left to try
result.Action = (settings.DeletedTabHandlingType == DeletedTabHandlingType.Do404Error)
? ActionType.Output404
: ActionType.Redirect301;
if (result.Action == ActionType.Redirect301)
{
result.Reason = RedirectReason.Deleted_Page;
result.DoRewrite = true;
result.FinalUrl = Globals.AddHTTP(result.PortalAlias.HTTPAlias + "/");
reWritten = true;
}
}
break;
}
}
}
result.FriendlyRewrite = reWritten;
result.DoRewrite = reWritten;
return newUrl;
}
internal static void GetUrlWithQuerystring(HttpRequest request, Uri requestUri, out string fullUrl, out string querystring)
{
// 699: incorrect encoding in absoluteUri.ToString()
string urlWoutQuery = requestUri.AbsoluteUri;
if (requestUri.Query != string.Empty)
{
urlWoutQuery = urlWoutQuery.Replace(requestUri.Query, string.Empty);
// replace the querystring on the reuqest absolute Uri
}
// 926 : do not use querystring.toString() because of encoding errors that restul,
// the encoding type is changed from utf-8 to latin-1
querystring = requestUri.Query;
// get results
fullUrl = urlWoutQuery;
if (fullUrl.EndsWith("/_noext.aspx", StringComparison.InvariantCultureIgnoreCase))
{
fullUrl = fullUrl.Replace("_noext.aspx", string.Empty);
// replace this marker pattern so it looks as though it isn't there *(leave on trailing slash)
}
if (querystring != string.Empty)
{
// set up the querystring and the fullUrl to include the querystring
if (querystring.StartsWith("?") == false)
{
querystring = "?" + querystring;
}
fullUrl += querystring;
}
}
/// <summary>Identifies a request for a physical file on the system.</summary>
/// <param name="physicalPath">The Physical Path property of the request.</param>
/// <param name="fullUrl"></param>
/// <param name="queryStringCol"></param>
/// <param name="result"></param>
/// <param name="useFriendlyUrls"></param>
/// <param name="settings"></param>
/// <param name="isPhysicalResource"></param>
/// <param name="checkFurtherForRewrite"></param>
/// <param name="parentTraceId"></param>
internal static void IdentifyByPhysicalResource(
string physicalPath,
string fullUrl,
NameValueCollection queryStringCol,
ref UrlAction result,
bool useFriendlyUrls,
FriendlyUrlSettings settings,
out bool isPhysicalResource,
out bool checkFurtherForRewrite,
Guid parentTraceId)
{
isPhysicalResource = false;
checkFurtherForRewrite = true;
if (File.Exists(physicalPath) && physicalPath.EndsWith("\\_noext.aspx") == false)
{
// resource found
string appPath = Globals.ApplicationMapPath + "\\default.aspx";
bool isDefaultAspxPath = false;
if (string.Compare(physicalPath, appPath, StringComparison.OrdinalIgnoreCase) != 0)
{
string aliasQs;
if (AdvancedUrlRewriter.CheckForChildPortalRootUrl(fullUrl, result, out aliasQs))
{
result.DebugMessages.Add("Child Portal Alias Root Identified");
}
else
{
// it's not the default.aspx path or a child alias request, so we haven't identifed the resource
isPhysicalResource = true;
checkFurtherForRewrite = false;
result.DebugMessages.Add("Resource Identified No Rewrite Used");
}
}
else
{
isDefaultAspxPath = true;
}
if (isDefaultAspxPath)
{
// it is the default aspx path
// check to see if it is a /default.aspx?key=value url (not just default.aspx, nor a child alias)
if (queryStringCol != null && queryStringCol.Count > 0)
{
// when there is a query string supplied, we don't need to rewrite
if (useFriendlyUrls)
{
// using friendly URls, so just nab the Tab id from the querystring
if (queryStringCol["tabId"] != null)
{
if (result.RedirectAllowed)
{
result.Action = ActionType.CheckFor301;
result.Reason = RedirectReason.Unfriendly_Url_TabId;
}
}
}
result.DoRewrite = false;
checkFurtherForRewrite = false;
// no more checking for rewrites, we have our physical file and our query string
// the default.aspx is still a physical resource, but we want to do the rest of the processing
}
else
{
// could be either default.aspx with no querystring, or a child portal alias root
// if 301 redirects are on, then we want to rewrite and replace this Url to include information like language modifiers
// so return false to indicate that the physical resource couldn't be identified
isPhysicalResource = !useFriendlyUrls;
}
}
}
// mark as physical request
result.IsPhysicalResource = isPhysicalResource;
}
internal static bool IdentifyByRegEx(
string absoluteUri,
string queryString,
string applicationPath,
ref UrlAction result,
FriendlyUrlSettings settings,
Guid parentTraceId)
{
var doRewrite = false;
var rewriterConfig = RewriterConfiguration.GetConfig();
if (rewriterConfig != null)
{
var url = absoluteUri; // get local copy because it gets hacked around
// Remove querystring if exists..
if (queryString != string.Empty)
{
url = url.Replace(queryString, string.Empty);
}
var rules = rewriterConfig.Rules;
if (rules == null)
{
throw new NullReferenceException("DotNetNuke.HttpModules.Config.RewriterRuleCollection is null");
}
for (var i = 0; i <= rules.Count - 1; i++)
{
// iterate the Config Rules looking for a match
var re = rules[i].GetRuleRegex(applicationPath);
if (re.IsMatch(url))
{
var sendTo = rules[i].SendTo;
// get a new rewritePath location
var rewritePath = RewriterUtils.ResolveUrl(applicationPath, re.Replace(url, sendTo)); // no rewrite path unless we match by regex the intended tab
var sesMatch = re.Match(url);
var sesUrlParams = sesMatch.Groups[2].Value;
// a match by regex means it's probably not a 'friendly' Url, so assume at this stage that this request will end up a 301
if (settings.UrlFormat == "advanced" && settings.RedirectUnfriendly)
{
result.Action = ActionType.CheckFor301;
}
// if a match is found here, there is the potential for a 'friendlier' url
if (sesUrlParams.Trim().Length > 0)
{
sesUrlParams = sesUrlParams.Replace("\\", "/");
var urlParams = sesUrlParams.Split('/');
for (var x = 1; x <= urlParams.Length - 1; x++)
{
if (urlParams[x].Trim().Length > 0 &&
!urlParams[x].Equals(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase))
{
rewritePath = rewritePath + "&" + urlParams[x].Replace(".aspx", string.Empty).Trim() + "=";
if (x < (urlParams.Length - 1))
{
x += 1;
if (urlParams[x].Trim() != string.Empty)
{
rewritePath = rewritePath + urlParams[x].Replace(".aspx", string.Empty);
}
}
}
}
}
// add back the query string if it was there
rewritePath = AddQueryStringToRewritePath(rewritePath, queryString);
// 832 : check for leading ~ - if not there, then redirect
if (sendTo.StartsWith("~"))
{
doRewrite = true;
SetRewriteParameters(ref result, rewritePath);
RedirectTokens.SetRedirectReasonAndAction(ref result, settings);
result.DoRewrite = true;
}
else
{
// we'll assume it's a 301 instead of a 302
result.Action = ActionType.Redirect301;
result.DoRewrite = false;
result.Reason = RedirectReason.SiteUrls_Config_Rule;
result.FinalUrl = rewritePath;
}
break; // exit loop, match found
}
}
}
return doRewrite;
}
internal static bool IdentifyByTabPathEx(
string absoluteUri,
string queryString,
UrlAction result,
NameValueCollection queryStringCol,
FriendlyUrlSettings settings,
Guid parentTraceId)
{
string scheme = result.Scheme;
if (absoluteUri.StartsWith(scheme, StringComparison.InvariantCultureIgnoreCase))
{
absoluteUri = absoluteUri.Substring(scheme.Length);
}
// Remove QueryString if it exists in the Url value
if (queryString != string.Empty)
{
absoluteUri = absoluteUri.Replace(queryString, string.Empty);
}
absoluteUri = HttpUtility.UrlDecode(absoluteUri); // decode the incoming request
string rewritePath = GetTabFromDictionary(absoluteUri, queryStringCol, settings, result, parentTraceId);
// put the query string back on the end
rewritePath = AddQueryStringToRewritePath(rewritePath, queryString);
// 810 : if a culture code is not specified in the rewrite path
if (result.DoRewrite && settings.ForcePortalDefaultLanguage && result.PortalId >= 0 &&
rewritePath.Contains("language=") == false)
{
// add the portal default language to the rewrite path
PortalInfo portal = CacheController.GetPortal(result.PortalId, false);
// DNN-3789 - culture is defined by GetPageLocale
string currentLocale = Localization.GetPageLocale(new PortalSettings(result.TabId, result.PortalAlias)).Name;
if (portal != null && !string.IsNullOrEmpty(currentLocale))
{
AddLanguageCodeToRewritePath(ref rewritePath, currentLocale);
result.CultureCode = currentLocale;
result.DebugMessages.Add("Current Language code " + currentLocale + " added");
}
}
// set the rewrite path
result.RewritePath = rewritePath;
return result.DoRewrite;
}
internal static bool IdentifyByTabQueryString(Uri requestUri, NameValueCollection queryStringCol, bool useFriendlyUrls, UrlAction result)
{
const bool doRewrite = false;
string requestedPath = requestUri.LocalPath;
if (useFriendlyUrls)
{
// using friendly URls, so just nab the Tab id from the querystring
if (result.RedirectAllowed && requestedPath.EndsWith(Globals.glbDefaultPage, StringComparison.OrdinalIgnoreCase)
&& (queryStringCol["tabId"] != null))
{
result.Action = ActionType.CheckFor301;
result.Reason = RedirectReason.Unfriendly_Url_TabId;
}
}
result.DoRewrite = doRewrite;
return doRewrite;
}
/// <summary>Replaces the core IsAdminTab call which was decommissioned for DNN 5.0.</summary>
/// <param name="portalId"></param>
/// <param name="tabPath">The path of the tab //admin//someothername.</param>
/// <param name="settings"></param>
/// <returns><see langword="true"/> if the page is an admin page, otherwise <see langword="false"/>.</returns>
internal static bool IsAdminTab(int portalId, string tabPath, FriendlyUrlSettings settings)
{
var portal = PortalController.Instance.GetPortal(portalId);
var adminTab = TabController.Instance.GetTab(portal.AdminTabId, portalId);
// return false if AdminTabId is -1, it could happen when a portal is in the middle of importing
if (adminTab == null)
{
return false;
}